//
//  CustomButton.m
//  事件响应机制
//
//  Created by 伍银荣 on 2020/7/6.
//  Copyright © 2020 com.example. All rights reserved.
//

/**
 需求:要求:一个矩形的button,要求只能点击矩形内圆形半径的范围,大于圆形半径的值的范围不可点击
 */



#import "CustomButton.h"

@implementation CustomButton

-(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    if (!self.userInteractionEnabled || self.isHidden || self.alpha <= 0.01) {
        return nil;
    }
    if ([self pointInside:point withEvent:event]) {
        //先创建一个局部的UIView类型的hit变量
        __block UIView *hit = nil;
        //NSEnumerationReverse:倒序遍历
        [self.subviews enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
           //把当前控件上的坐标系转换成子控件上的坐标系
            CGPoint convertPoint = [self convertPoint:point toView:obj];
            //调用子视图的hitTest:方法
            hit = [obj hitTest:convertPoint withEvent:event];
            //如果当前点击的view在这个视图范围内,就停止遍历
            if (hit) {
                *stop = YES;
            }
        }];
        if (hit) {
            return hit;
        } else {
            return self;
        }
    } else {
      return nil;
    }
}

-(BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
    CGFloat x1 = point.x;
    CGFloat y1 = point.y;
    
    //获取button的中心点
    CGFloat x2 = self.frame.size.width / 2;
    CGFloat y2 = self.frame.size.height / 2;
    
    
    
    //计算两点间的距离
    double distent = sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
    
    //判断两点间的间距是否小于圆形半径,如果小于,则可以点击,如果大于,则不能点击
    if (distent <= self.frame.size.width / 2) {
        return YES;
    } else {
        return NO;
    }
}







/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
